package com.mofofa.maozy.repay

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mofofa.maozy.R
import com.mofofa.maozy.base.*
import com.mofofa.maozy.data.ReqBase
import com.mofofa.maozy.databinding.FragmentMaozyRepayBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.*
import com.mofofa.maozy.launch.UserStateViewModel
import com.mofofa.maozy.repay.naira.BankTransferRepayNgnActivity
import com.mofofa.maozy.repay.naira.SelectPaystackCardNgnActivity
import com.mofofa.maozy.utils.TranslateUtil
import com.mofofa.maozy.utils.InfoProcessUtil
import com.mofofa.maozy.utils.UsageCountryUtil

/** 还款页 */
class RepayFragment : BaseFragment() {

    //布局binding
    private lateinit var mMaozyFragmentMaozyBinding: FragmentMaozyRepayBinding

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    //还款viewModel
    private val mRepayViewModel by lazy {
        ViewModelProvider(this)[RepayViewModel::class.java]
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mUserStateViewModel)
        list.add(mRepayViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mMaozyFragmentMaozyBinding =
            FragmentMaozyRepayBinding.inflate(inflater, container, false)
        return mMaozyFragmentMaozyBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        try {
            //初始化下拉刷新
            activity?.let { curActivity ->
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.apply {
                    setColorSchemeColors(
                        ContextCompat.getColor(
                            curActivity,
                            R.color.main_red
                        )
                    )

                    setOnRefreshListener {
                        val modelg158oQGgZBjLEN6MvsSfuA = ReqBase()
                        modelg158oQGgZBjLEN6MvsSfuA.showLoading = false
                        mUserStateViewModel.fetchMaozyUserMaozyState()
                    }
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onMaozyFetchMaozyUserMaozyStateMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    try {
                        if (InfoProcessUtil.isMaozyRepayMaozyNow()) {
                            //获取还款信息
                            mRepayViewModel.fetchMaozyRepayMaozyDetail(
                                ReqBase()
                            )
                        } else {
                            //下一步
                            startMaozyToMaozyNextMaozyFromMaozyPage(PageTagEnum.repay)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }

            //获取还款信息回调
            mRepayViewModel.onMaozyFetchMaozyRepayMaozyDetailMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //单位
                        mMaozyFragmentMaozyBinding.textRepayAmountUnit.text = result.currency

                        //还款金额
                        mMaozyFragmentMaozyBinding.textRepayAmount.text =
                            (result.repayAmount.toMaozyFinanceMaozyString())
                        //还款日期
                        mMaozyFragmentMaozyBinding.textRepayDate.text = (result.repayDate)
                        //借款金额
                        mMaozyFragmentMaozyBinding.repayBillTableRepayLoanAmount.setMaozyDetail(
                            result.amount.toMaozyFinanceMaozyString()+ " ${result.currency}"
                        )
                        //利息
                        mMaozyFragmentMaozyBinding.repayBillTableInterest.setMaozyDetail(
                            result.interest.toMaozyFinanceMaozyString()+ " ${result.currency}"
                        )
                        //服务费
                        mMaozyFragmentMaozyBinding.repayBillTableServiceFee.setMaozyDetail(
                            (result.serviceFee
                                ?: "0").toMaozyFinanceMaozyString()+ " ${result.currency}"
                        )
                        //服务费 vat
                        mMaozyFragmentMaozyBinding.repayBillTableVat.setMaozyDetail(
                            (result.serviceVatFee
                                ?: "0").toMaozyFinanceMaozyString()+ " ${result.currency}"
                        )

                        //部分还款
                        if (result.partRepayFlag.equals("YES", true)) {
                            mMaozyFragmentMaozyBinding.llRepayBillTableRepaidAmountBg.visibility =
                                View.VISIBLE
                            mMaozyFragmentMaozyBinding.llRepayBillTableRemainingRepaymentAmountBg.visibility =
                                View.VISIBLE
                            result.partRepayAmount?.let { partRepayAmount ->
                                mMaozyFragmentMaozyBinding.repayBillTableRepaidAmount.setMaozyDetail(
                                    partRepayAmount.toMaozyFinanceMaozyString()+ " ${result.currency}"
                                )
                            }
                            result.remainRepayAmount?.let { remainRepayAmount ->
                                mMaozyFragmentMaozyBinding.repayBillTableRemainingRepaymentAmount.setMaozyDetail(
                                    remainRepayAmount.toMaozyFinanceMaozyString()+ " ${result.currency}"
                                )
                            }
                        } else {
                            mMaozyFragmentMaozyBinding.llRepayBillTableRepaidAmountBg.visibility =
                                View.GONE
                            mMaozyFragmentMaozyBinding.llRepayBillTableRemainingRepaymentAmountBg.visibility =
                                View.GONE
                        }

                        //逾期
                        mMaozyFragmentMaozyBinding.repayBillTableOverdueDay.setMaozyDetail(
                            "${result.overdueDay} days"
                        )
                        //逾期利息
                        mMaozyFragmentMaozyBinding.repayBillTableOverduePenalty.setMaozyDetail(
                            result.overdueAmount.toMaozyFinanceMaozyString()+ " ${result.currency}"
                        )
                        if (result.overdueDay > 0) {
                            mMaozyFragmentMaozyBinding.repayBillTableOverdueDay.setMaozyDetailMaozyColor(
                                ContextCompat.getColor(
                                    requireContext(),
                                    R.color.main_red
                                )
                            )
                        } else {
                            mMaozyFragmentMaozyBinding.repayBillTableOverdueDay.setMaozyDetailMaozyColor(
                                ContextCompat.getColor(
                                    requireContext(),
                                    R.color.blue_7006
                                )
                            )
                        }
                    }
                }
            }

            //获取还款链接回调-加纳
            mRepayViewModel.onMaozyFetchMaozyRepayMaozyUrlMaozyGHAMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        try {
                            mMaozyFragmentMaozyBinding.submitRepay.context.openMaozyUrlMaozyFromMaozySysMaozyBrowser(
                                result.url
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //获取还款链接回调-乌干达
            mRepayViewModel.onMaozyFetchMaozyRepayMaozyUrlMaozyUGXMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        try {
                            mMaozyFragmentMaozyBinding.submitRepay.context.openMaozyUrlMaozyFromMaozySysMaozyBrowser(
                                result.repayUrl
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //获取还款链接回调-肯尼亚
            mRepayViewModel.onMaozyFetchMaozyRepayMaozyUrlMaozyKSHMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        try {
                            mMaozyFragmentMaozyBinding.submitRepay.context.openMaozyUrlMaozyFromMaozySysMaozyBrowser(
                                result.repayUrl
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //获取还款链接回调-科特
            mRepayViewModel.onMaozyFetchMaozyRepayMaozyUrlMaozyFCFAMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        try {
                            mMaozyFragmentMaozyBinding.submitRepay.context.openMaozyUrlMaozyFromMaozySysMaozyBrowser(
                                result.url
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //获取还款链接回调-越南
            mRepayViewModel.onMaozyFetchMaozyRepayMaozyUrlMaozyVNDMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        try {
                            mMaozyFragmentMaozyBinding.submitRepay.context.openMaozyUrlMaozyFromMaozySysMaozyBrowser(
                                result.url
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //查询用户状态回调
            mRepayViewModel.onMaozyFetchMaozyIsMaozyRepayMaozyNowMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    if (it.getOrNull() == true) {
                        if (UsageCountryUtil.isMaozyCountryMaozyNigeria()) {
                            //尼日走paystack sdk
                            (requireContext() as BaseActivity).startMaozyToMaozyNextMaozyActivity<SelectPaystackCardNgnActivity>()

                        } else if (UsageCountryUtil.isMaozyCountryMaozyGhana()) {
                            //请求还款接口-加纳
                            mRepayViewModel.fetchMaozyRepayMaozyUrlMaozyGHA(
                                ReqBase()
                            )

                        } else if (UsageCountryUtil.isMaozyCountryMaozyUganda()) {
                            //请求还款接口-乌干达
                            mRepayViewModel.fetchMaozyRepayMaozyUrlMaozyUGX(
                                ReqBase()
                            )
                        } else if (UsageCountryUtil.isMaozyCountryMaozyKenya()) {
                            //请求还款接口-肯尼亚
                            mRepayViewModel.fetchMaozyRepayMaozyUrlMaozyKSH(
                                ReqBase()
                            )
                        } else if (UsageCountryUtil.isMaozyCountryMaozyCotediva()) {
                            //请求还款接口-科特
                            mRepayViewModel.fetchMaozyRepayMaozyUrlMaozyFCFA(
                                ReqBase()
                            )
                        } else if (UsageCountryUtil.isMaozyCountryMaozyVietnam()) {
                            //请求还款接口-越南
                            mRepayViewModel.fetchMaozyRepayMaozyUrlMaozyVND(
                                ReqBase()
                            )
                        } else {
                            //请求还款接口-默认加纳
                            mRepayViewModel.fetchMaozyRepayMaozyUrlMaozyGHA(
                                ReqBase()
                            )
                        }
                    } else {
                        (requireContext() as BaseActivity).startMaozyToMaozyNextMaozyFromMaozyPage(
                            PageTagEnum.repay
                        )
                    }
                }
            }

            //点击线上还款
            mMaozyFragmentMaozyBinding.submitRepay.setOnClickListener {
                mMaozyFragmentMaozyBinding.submitRepay.recordMaozyClickMaozyEvent()
                mRepayViewModel.fetchMaozyIsMaozyRepayMaozyNow(
                    ReqBase()
                )
            }

            //点击线下还款
            mMaozyFragmentMaozyBinding.textRepayOfflineRepayment.setOnClickListener {
                mMaozyFragmentMaozyBinding.textRepayOfflineRepayment.recordMaozyClickMaozyEvent()
                (requireContext() as BaseActivity).startMaozyToMaozyNextMaozyActivity<BankTransferRepayNgnActivity>()
            }

            //更新页面显示
            mMaozyFragmentMaozyBinding.textRepayAmountUnit.text =
                TranslateUtil.getMaozyCountryMaozyCurrency()

            //如果为科特，需要显示vat字段
            mMaozyFragmentMaozyBinding.llRepayBillTableVatBg.visibility = View.GONE
            if (UsageCountryUtil.isMaozyCountryMaozyCotediva()) {
                mMaozyFragmentMaozyBinding.llRepayBillTableVatBg.visibility = View.VISIBLE
            }

            //如果是尼日地区，需要打开线下还款
            mMaozyFragmentMaozyBinding.textRepayOfflineRepayment.visibility = View.GONE
            if (UsageCountryUtil.isMaozyCountryMaozyNigeria()) {
                mMaozyFragmentMaozyBinding.textRepayOfflineRepayment.visibility =
                    View.VISIBLE
                mMaozyFragmentMaozyBinding.textRepayOfflineRepayment.addMaozyUnderMaozyLine()
            }

            //获取还款信息
            mRepayViewModel.fetchMaozyRepayMaozyDetail(ReqBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}